package com.vercon.moensmart.dialog

import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.vercon.common.Constants
import com.vercon.common.presenter.common.MirrorResultView
import com.vercon.common.utils.APPUtil
import com.vercon.common.utils.MirrorDataStorage
import com.vercon.moensmart.MainActivity
import com.vercon.moensmart.databinding.DialogLoginLayoutBinding
import com.vercon.moensmart.fragment.base.BaseFragment
import com.vercon.moensmart.fragment.manager.FragmentOpenManager
import com.vercon.moensmart.fragment.setting.WiFiFragment
import com.vercon.moensmart.mode.LocalUserInfo
import com.vercon.moensmart.mode.response.MoenToken
import com.vercon.moensmart.presenter.MoenPresenter
import com.vercon.moensmart.utils.ToastUtils
import com.vercon.moensmart.viewmodel.SystemViewModel

class LoginDialog : BaseFragment<DialogLoginLayoutBinding>() {

    var moenPresenter = MoenPresenter()
    var systemViewModel : SystemViewModel? = null
    private var index = 1 //点击10次，打开设置页

    override fun onCreateViewBinding(inflater: LayoutInflater, parent: ViewGroup?): DialogLoginLayoutBinding {
       return DialogLoginLayoutBinding.inflate(inflater,parent,false)
    }

    override fun initData() {
        MirrorDataStorage.instance().storeString(Constants.STORAGE_KEY_TOKEN,"")
        val localUserInfo = MirrorDataStorage.instance().getString(Constants.USER_INFO, "")
        if(!localUserInfo.isNullOrEmpty()){
            val userInfo = Gson().fromJson(localUserInfo,LocalUserInfo::class.java)
            binding?.igSave?.isSelected = userInfo.isSave
            binding?.etUsername?.setText(userInfo.username)
            binding?.etPassword?.setText(userInfo.password)
        }
        systemViewModel = ViewModelProvider(requireActivity())[SystemViewModel::class.java]
    }

    override fun initListener() {

        binding?.tvGoToSystem?.setOnClickListener(View.OnClickListener {
            if (index >= 9) {
                index = 1
                startActivity(Intent(Settings.ACTION_SETTINGS))
                APPUtil.addPackageName("com.android.settings.Settings")
            } else {
                index += 1
            }
        })

        binding?.rlMain?.setOnClickListener {
            hideKeyboard(binding?.etUsername)
        }
        binding?.rlBase?.setOnClickListener {
            hideKeyboard(binding?.etUsername)
        }
        binding?.igWifi?.setOnClickListener {
            FragmentOpenManager.getInstance().addFragment(requireActivity(),WiFiFragment())
        }

        binding?.llRememberMe?.setOnClickListener {
            binding?.igSave?.isSelected =  !binding?.igSave?.isSelected!!
        }

        binding?.tvLogin?.setOnClickListener {
            getToken(binding?.etUsername?.text.toString().trim(),binding?.etPassword?.text.toString().trim())
        }

        binding?.igClose?.setOnClickListener {
            FragmentOpenManager.getInstance().closeFragment(activity!!)
        }
    }

    override fun onClick(v: View?) {

    }



    private fun getToken(userName : String,password : String){
        binding?.llLoading?.visibility = View.VISIBLE
        moenPresenter.getMoenToken(userName,password,object : MirrorResultView<MoenToken> {

            override fun onSuccess(result: MoenToken?) {
                binding?.llLoading?.visibility = View.GONE
                MirrorDataStorage.instance().storeString(Constants.STORAGE_KEY_TOKEN, result?.token?.access_token)
                systemViewModel?.setUserTokenLiveData(result?.token?.access_token)

                val username : String = binding?.etUsername?.text.toString().trim()
                val password : String = binding?.etPassword?.text.toString().trim()
                val isSave : Boolean = binding?.igSave?.isSelected!!
                if(isSave){
                    MirrorDataStorage.instance().storeString(Constants.USER_INFO, Gson().toJson(LocalUserInfo(username,password,isSave)))
                }else{
                    MirrorDataStorage.instance().storeString(Constants.USER_INFO, "")
                }

                hideKeyboard(binding?.etUsername)
                FragmentOpenManager.getInstance().closeFragment(activity!!)
                FragmentOpenManager.getInstance().goToHomeFragment(activity!!)
            }
            override fun onError(code: Int, message: String?) {
                ToastUtils.showToast("登录失败")
                binding?.llLoading?.visibility = View.GONE
            }
        })

    }

    fun hideKeyboard(token: View?) {
        if (token != null) {
            val im = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

}